package com.hcm.module.gzfk.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hcm.kernel.mvc.ctrl.KernelCtrl;
import com.hcm.kernel.util.JSONUtil;
import com.hcm.kernel.util.MyBigDecimal;
import com.hcm.kernel.util.Pagination;
import com.hcm.kernel.util.RandomUtil;
import com.hcm.kernel.web.annotation.WebToken;
import com.hcm.kernel.wechat.MsgAPI;
import com.hcm.module.admin.model.User;
import com.hcm.module.admin.service.IUserService;
import com.hcm.module.gzfk.ctrl.util.GAuthAPI;
import com.hcm.module.gzfk.model.CashLog;
import com.hcm.module.gzfk.model.PayStream;
import com.hcm.module.gzfk.model.Trade;
import com.hcm.module.gzfk.model.TradeLog;
import com.hcm.module.gzfk.service.impl.GoodsService;
import com.hcm.module.gzfk.service.impl.PayStreamService;
import com.hcm.module.gzfk.service.impl.TradeLogService;
import com.hcm.module.gzfk.service.impl.TradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 所有页面中操作
 */
@Controller
@RequestMapping("/wx")
public class WXIndexCtrl extends KernelCtrl {

    @Autowired
    GoodsService goodsService;
    @Autowired
    TradeLogService tradeLogService;
    @Autowired
    TradeService tradeService;
    @Autowired
    IUserService userService;
    @Autowired
    PayStreamService payStreamService;

    @RequestMapping("/index")
    @WebToken(add=true)
    public String index(ModelMap mm,HttpSession session){
        User user = (User)session.getAttribute("user");
        if(user==null) {
            user = userService.findByCode("op2cJuMSzWvOmIEHzv8VQX1-jM8c");
            session.setAttribute("user",user);
            return "redirect_url";
        }

        //获取价格
        List<Map<String,Object>> list = goodsService.lastNew(user.getCode());
        for (Map<String,Object> m : list) {
            if(m.get("tid")!=null){
                MyBigDecimal price = new MyBigDecimal(m.get("price").toString());
                MyBigDecimal yk = null;
                if("多".equals(m.get("xtype"))){
                    MyBigDecimal sell = new MyBigDecimal(m.get("sell").toString());
                    m.put("closePrice",sell);
                    yk = sell.subtract(price);
                }
                if("空".equals(m.get("xtype"))){
                    MyBigDecimal buy = new MyBigDecimal(m.get("buy").toString());
                    m.put("closePrice",buy);
                    yk = price.subtract(buy);
                }

                if(m.get("type").equals("sliver")) {
                    yk = yk.divide(new MyBigDecimal(10));
                }
                m.put("yk",yk);
                m.put("yk_per",yk.divide(new MyBigDecimal(m.get("pay").toString()),3, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));
            }
            mm.put(m.get("type").toString(),m);
            mm.put(m.get("type").toString()+"_", JSONUtil.toJSONString(m));
        }
        mm.put("goods",JSONUtil.toJSONString(mm));

        //获取交易历史
        List<TradeLog> tLogList = tradeLogService.findByEntity(new TradeLog(),new Pagination(1));
        mm.put("logList",tLogList);

        //交易历史汇总
        mm.put("logCount",tradeLogService.findCount());

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int date = calendar.get(Calendar.DAY_OF_WEEK);
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        if(date ==1 || date ==7 || h>=4 && h<7){
            mm.put("mask",true);//闭市时间
        }

        return "wx/index";
    }

    @RequestMapping("/price")
    public String price(ModelMap mm,HttpSession session){
        User user = (User)session.getAttribute("user");
        //获取价格
        List<Map<String,Object>> list = goodsService.lastNew(user.getCode());
        for (Map<String,Object> m : list) {
            if(m.get("tid")!=null){
                MyBigDecimal price = new MyBigDecimal(m.get("price").toString());
                MyBigDecimal yk = null;
                if("多".equals(m.get("xtype"))){
                    MyBigDecimal sell = new MyBigDecimal(m.get("sell").toString());
                    m.put("closePrice",sell);
                    yk = sell.subtract(price);
                }
                if("空".equals(m.get("xtype"))){
                    MyBigDecimal buy = new MyBigDecimal(m.get("buy").toString());
                    m.put("closePrice",buy);
                    yk = price.subtract(buy);
                }

                if(m.get("type").equals("sliver")) {
                    yk = yk.divide(new MyBigDecimal(10));
                }
                m.put("yk",yk);
                m.put("yk_per",yk.divide(new MyBigDecimal(m.get("pay").toString()),3, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));
            }
            mm.put(m.get("type").toString(),m);
            mm.put(m.get("type").toString()+"_", JSONUtil.toJSONString(m));
        }
        mm.put("goods",JSONUtil.toJSONString(mm));

        return "wx/module/tab";
    }



    /**
     *
     * @param type 类型
     * @param xtype 持仓类型 多 空
     * @param price 建仓价格
     * @param
     * @param gain
     * @param loss
     * @param session
     * @param mm
     * @return
     */
    @WebToken(valid = true)
    @RequestMapping("/holding")//holding stock
    public String holding(String type,String xtype,String price,MyBigDecimal pay,int gain,int loss,HttpSession session,ModelMap mm){
        User user = (User)session.getAttribute("user");

        //检查用户，要求余额要大于保险金，或者如果用户第一次登录时赠送一个，当然现在用户在注册时已将loginNum设置为2
        if(user.getPay().compareTo(pay)>=0 || user.getLoginNum() == 1){
            Trade trade = new Trade();
            trade.setType(type);
            if(trade.getType().equals("gold"))
                trade.setName("黄金");
            else if(trade.getType().equals("sliver"))
                trade.setName("白银");
            else if(trade.getType().equals("oil"))
                trade.setName("原油");

            trade.setXtype(xtype);
            trade.setPrice(new MyBigDecimal(price));//买入价
            trade.setPay(pay);
            trade.setGainPer(gain);
            trade.setLossPer(loss);
            trade.setOpenId(user.getCode());
            trade.setCreateTime(new Timestamp(System.currentTimeMillis()));
            trade.setTradeNo(RandomUtil.random());//订单号
            trade.setNickName(user.getWeChatName());//微信名

            //mm.put("msg","建仓已完成。");改为发送消息
            MsgAPI.send(trade.getOpenId(), "建仓成功：老板，你眼光真好， " + trade.getName() + "在￥" + trade.getPrice() + "成功做" + trade.getXtype() + "，预祝盈利稳稳哒！\n" +
                    "温馨提醒：当天闭市前必须平仓，否则系统自动平仓！");

            PayStream ps = null;
            //if(user.getLoginNum() != 1) {//如是用户不是第一次登录，将扣保证金及记录流水
                ps  = new PayStream();
                ps.setOpenId(user.getCode());
                ps.setCreateTime(new Timestamp(System.currentTimeMillis()));
                ps.setBeforePay(user.getPay());
                user.setPay(user.getPay().subtract(pay));
                ps.setPay(MyBigDecimal.ZERO.subtract(pay));
                ps.setAfterPay(user.getPay());
                ps.setType("扣保证金（"+trade.getName()+"）");
            //}
            user.setLoginNum(user.getLoginNum() + 1);
            tradeService.trade(trade, user, ps);

            session.setAttribute("user",user);
            mm.put("t"+trade.getType(),trade);
        }else{
            //mm.put("msg","保证金不足，请充值。");
            MsgAPI.send(user.getCode(),"余额不足：哎呀，肚子扁扁可是没有力气干活的！请点击屏幕上面的充值。");
        }

        return "redirect:/wx/index.htm";
    }

    @WebToken(valid = true)
    @RequestMapping("/close")//close stock
    public String close(String type,HttpSession session){
        User user = (User)session.getAttribute("user");
        user = userService.close(user.getCode(), type);
        if(user!=null) {
            session.setAttribute("user", user);
        }

        return "redirect:/wx/index.htm";
    }

    //刷新购买人数
    @RequestMapping("/refreshLog")
    public String refresh(ModelMap mm){
        mm.put("log",tradeLogService.getLast());
        return "wx/module/log";
    }

    //提现
    @WebToken(valid = true)
    @RequestMapping("/saveMore")
    public String saveMore(String name,String mobile,HttpSession session,ModelMap mm){
        User user = (User)session.getAttribute("user");
        user.setPhone(mobile);
        user.setWeChat(name);
        CashLog cash = userService.cash(user);
        mm.put("msg",cash.getAttr0());
        if(cash.getAttr1().equals("success")){
            user.setPay(MyBigDecimal.ZERO);
        }
        session.setAttribute("user",user);
        return index(mm,session);
    }

    /**
     * 个人交易历史
     * @return
     */
    @RequestMapping("/log")
    public String log(String code,ModelMap mm){
        String json = GAuthAPI.getUserOpenid(code);//"{'openid':'op2cJuMSzWvOmIEHzv8VQX1-jM8c'}";//
        JSONObject object = JSON.parseObject(json);

        List<?> list = tradeLogService.findLastByCode(object.getString("openid"));

        mm.put("list",list);
        return "wx/info/myLog";
    }

}
